/**
 * 剑指 Offer 67. 把字符串转换成整数
 * https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
 */
public class Solutions_Offer_67 {
    public static void main(String[] args) {
//        String str = "42";  // output: 42
//        String str = "   -42";  // output: -42
//        String str = "4193 with words";  // output: 4193
        String str = "words and 987";  // output: 0
//        String str = "-91283472332";  // output: -2147483648
//        String str = "+1";  // output: 1

        int result = strToInt(str);
        System.out.println(result);
    }

    public static int strToInt(String str) {
        long res = 0;
        char[] arr = str.toCharArray();
        int i = 0;
        int len = arr.length;
        while (i < len && arr[i] == ' ') {
            // 去除空格
            i++;
        }
        // 系数（有负号时，系数为 -1，默认为 1，即正数）
        int flag = 1;
        if (i < len && (arr[i] == '-' || arr[i] == '+')) {
            flag = arr[i] == '-' ? -1 : 1;
            i++;
        }
        for (; i < len; i++) {
            if (Character.isDigit(arr[i])) {
                res = res * 10 + (arr[i] - '0');
                if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
                    // 越界时，根据符号返回最大/最小值
                    return flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
            } else {
                // 数字必须是连续的
                break;
            }
        }
        return ((int) res) * flag;
    }
}
